import pvporcupine
import pyaudio
import struct

def wait_for_wakeup(callback=None, access_key="你的Picovoice访问密钥", keyword_paths=None):
    """
    使用Porcupine等待唤醒词检测，检测到后执行callback。
    :param callback: 检测到唤醒词后执行的回调函数
    :param access_key: Picovoice访问密钥
    :param keyword_paths: 唤醒词模型路径列表，None则使用默认英文唤醒词
    """
    try:
        # 创建Porcupine实例
        if keyword_paths:
            porcupine = pvporcupine.create(
                access_key=access_key,
                keyword_paths=keyword_paths
            )
        else:
            # 使用默认英文唤醒词 "Picovoice"
            porcupine = pvporcupine.create(
                access_key=access_key,
                keywords=['picovoice']
            )
        
        # 初始化音频输入
        pa = pyaudio.PyAudio()
        audio_stream = pa.open(
            rate=porcupine.sample_rate,
            channels=1,
            format=pyaudio.paInt16,
            input=True,
            frames_per_buffer=porcupine.frame_length
        )
        
        print("唤醒模块已启动，等待唤醒词...")
        
        try:
            while True:
                # 读取音频数据
                pcm = audio_stream.read(porcupine.frame_length)
                pcm_unpacked = struct.unpack_from("h" * porcupine.frame_length, pcm)
                
                # 检测唤醒词
                keyword_index = porcupine.process(pcm_unpacked)
                if keyword_index >= 0:
                    print("唤醒词检测到！")
                    if callback:
                        callback()
                    break
                        
        finally:
            audio_stream.close()
            pa.terminate()
            porcupine.delete()
            
    except Exception as e:
        print(f"唤醒模块异常: {e}") 